<?php


namespace App\Service\PushService;


use Service\AppService\IdService;
use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Service\HttpRequest\Http;
use App\Service\TaskServer\TaskWorker;

class BusinessPushService extends BaseService
{
    /**
     * 推送渠道商消息
     * @param string $messageTye
     * @param array $binfo
     * @param array $body
     * @return unknown[]|string[]|array[]
     */
    public function pushMessage(string $messageTye, array $binfo = [] , array $body = [] )
    {
        if($binfo['is_push_goods'] == 1 ) {
            //是否多店铺模式（1-是，0-不是）
            if( $binfo['is_mult_shop'] == 1 ) {
                $notify_module = ucfirst($binfo['user_tag']);
            } else {
                $notify_module = ucfirst($binfo['account']);
            }
            $serviceClass   = "App\\Service\\UserService\\{$notify_module}Service";
            if( !class_exists($serviceClass) ) {
                return Normal::returnCode(Normal::FAIL,"{$serviceClass} not existed");
            }
            $requestMethod = 'orderAfterSale';
            if( !method_exists($serviceClass,$requestMethod) ) {
                return Normal::returnCode(Normal::FAIL,"{$serviceClass} {$requestMethod} methods not existed");
            }
            $param=[
                "binfo" =>$binfo,
                "order" =>$body,
            ];
            return $serviceClass::instance()->$requestMethod($param);
        }else{
            //属于下游电商平台对接云仓系统的商户，需要判断推送地址open_url是否为空
            if( empty($binfo['open_url']) ) {
                return Normal::returnCode(Normal::FAIL,"未配置接收物流信息地址");
            }
            
            $notify_message = [
                'MessageType'   => $messageTye,
                'data'          => $body,
                'datetime'      => time()
            ];
            $signArr = $notify_message;
            $signArr['data'] = rawurlencode(json_encode($signArr['data']));
            $sign = Http::getSign($signArr,$binfo['secret']);
            $notify_message['sign'] = strtoupper($sign);
            //开始推送数据
            $parameter = [
                [
                    'tag'       => $messageTye.'_'.$binfo['bid'],
                    'uid'       => IdService::instance()->getOtherID(),
                    'url'       => $binfo['open_url'],
                    'data'      => $notify_message,
                    'method'    => 'post',
                    'format'    => 'json',
                    'header'    => [
                        "Content-Type: application/json",
                        "User-Agent: micro_server"
                    ],
                ],
            ];
            $resTask = TaskWorker::instance()->addTask($parameter);
            $resTask = current($resTask);
            $res = $resTask['response']['result'];
            $resHttp = json_decode($res, true);
            
            //如果响应http code 不为200，抛错
            if( $resTask['response']['httpCode'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"下游电商平台接收物流信息接口响应失败，请重试【{$resTask['response']['httpCode']}】",['httpcode'=>$resTask['response']['httpCode']]);
            }
    
            //判断下游电商平台返回数据
            $res = $this->getReturnErrCode($resHttp);
            if( $res['code'] != Normal::SUC ) {
                return Normal::returnCode(Normal::FAIL,"下游电商平台接收物流信息接口处理失败，请重试【{$res['msg']}】");
            }
            return Normal::returnCode(Normal::SUC,"推送消息成功",[
                'data' => $notify_message
            ]);
        }
    }

    /**
     * 处理错误异常CODE
     */
    public function getReturnErrCode( $result = [] )
    {
        //货柜里商户
        if ( isset($result['code']) && $result['code'] != Normal::SUC ) {
            return Normal::returnCode(Normal::FAIL, isset($result['msg']) ? $result['msg'] : '推送失败',$result);
            //小蜜桃
        } elseif ( isset($result['errcode']) && $result['errcode'] != 0 ) {
            return Normal::returnCode(Normal::FAIL, isset($result['errmsg']) ? $result['errmsg'] : '推送失败',$result);
        } else {
            return Normal::returnCode(Normal::SUC,"接收处理成功");
        }
    }

}